﻿using System;
using System.Collections.Concurrent;
using System.Threading;

namespace Utils
{
    public class NotifyQueueHandler<T>
    {
        private readonly ConcurrentDictionary<Guid, T> waitObject = new ConcurrentDictionary<Guid, T>();

        private readonly ConcurrentQueue<(ManualResetEvent manualReset, Guid guid)> manualResets = new ConcurrentQueue<(ManualResetEvent, Guid)>();



        /// <summary>
        /// 等待一个结果
        /// </summary>
        /// <param name="key"></param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public bool WaitResult(Action begin, out T result, int timeout = 3000)
        {
            using (var manualResetEvent = new ManualResetEvent(false))
            {
                var guid = Guid.NewGuid();
                manualResets.Enqueue((manualResetEvent, guid));

                begin?.Invoke();
                if (manualResetEvent.WaitOne(timeout))
                {
                    if (waitObject.TryGetValue(guid, out result))
                    {
                        return true;
                    }
                }
                result = default;
                return false;
            }
        }


        /// <summary>
        /// 发送结果通知
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public bool Notify(T value)
        {
            if (manualResets.TryDequeue(out var manualReset))
            {
                waitObject.TryAdd(manualReset.guid, value);
                manualReset.manualReset.Set();
                return true;
            }
            return false;
        }

    }

}
